package com.zycfc.zsf.boot.job.api;

import org.springframework.beans.factory.annotation.*;
import com.dangdang.ddframe.job.api.*;
import com.zycfc.zsf.boot.util.time.*;
import java.util.stream.*;
import com.zycfc.zsf.boot.util.json.*;
import java.util.*;
import com.zycfc.zsf.boot.job.core.*;
import com.dangdang.ddframe.job.reg.zookeeper.*;
import com.zycfc.zsf.boot.core.common.*;
import com.zycfc.zsf.boot.logback.util.*;
import com.zycfc.zsf.boot.common.context.*;
import com.zycfc.zsf.boot.job.common.*;
import com.zycfc.zsf.boot.exception.*;
import com.zycfc.zsf.boot.util.text.*;
import com.zycfc.zsf.boot.job.api.domain.*;
import com.zycfc.zsf.boot.job.api.util.*;
import com.zycfc.zsf.boot.job.enums.*;
import com.zycfc.zsf.boot.localcache.cache.*;
import com.zycfc.zsf.boot.job.*;
import org.springframework.util.*;
import java.util.concurrent.locks.*;
import com.zycfc.zsf.boot.distributedlock.*;
import com.zycfc.zsf.boot.util.net.*;
import com.zycfc.zsf.boot.job.service.*;
import org.slf4j.*;

public abstract class AbstractSimpleJob implements BaseSimpleJob
{
    private static final Logger log;
    private static final String SUCCESS = "S";
    private static final String FAILURE = "F";
    private static final String IDENTMENT = "D";
    public static final String READY = "R";
    public static final String OVERFLOW = "O";
    @Value("${spring.profiles.active:local}")
    String profilesActive;
    private static final String ZSF_JOB_LOCK_GROUP = "ZSF_JOB_LOCK_GROUP";
    private static final long LOCK_TIME = 30000L;
    
    public void execute(final ShardingContext shardingContext) {
        JobProcessData data = new JobProcessData();
        data.setBizDate(this.getBizDate());
        data.setStartTm(DateUtils.getCurDT() + DateUtils.getCurTM());
        data.setStartTime(System.currentTimeMillis());
        data.setContext(shardingContext);
        try {
            data = this.before(data);
            if (!data.isSkip()) {
                AbstractSimpleJob.log.info("ZsfJob: \u51c6\u5907\u6267\u884c\u4efb\u52a1[{}].process(), \u5f53\u524d\u5206\u7247[{}]", (Object)shardingContext.getJobName(), (Object)shardingContext.getShardingItem());
                this.process(data);
                AbstractSimpleJob.log.info("ZsfJob: \u6267\u884c\u4efb\u52a1[{}].process()\u6210\u529f, \u5f53\u524d\u5206\u7247[{}]", (Object)shardingContext.getJobName(), (Object)shardingContext.getShardingItem());
                this.persistBizDate(data);
            }
            else if (!this.isSwitchOff()) {
                AbstractSimpleJob.log.info("[{}]\u672c\u6279\u6b21\u5df2\u7ecf\u6267\u884c\u6210\u529f\uff0c\u4e0d\u5728\u6267\u884c", (Object)shardingContext.getJobName());
            }
            data.setResultFlag(true);
        }
        catch (Exception e) {
            AbstractSimpleJob.log.error("ZsfJob: AbstractSimpleJob.execute()\u6267\u884c\u5f02\u5e38, \u4efb\u52a1\u540d\u79f0: [{}], \u9519\u8bef\u4fe1\u606f: [{}]", new Object[] { shardingContext.getJobName(), e.getMessage(), e });
            try {
                this.after(data);
            }
            catch (Exception e) {
                AbstractSimpleJob.log.error("ZsfJob: AbstractSimpleJob.after()\u6267\u884c\u5f02\u5e38, \u4efb\u52a1\u540d\u79f0: [{}]", (Object)shardingContext.getJobName(), (Object)e);
            }
        }
        finally {
            try {
                this.after(data);
            }
            catch (Exception e2) {
                AbstractSimpleJob.log.error("ZsfJob: AbstractSimpleJob.after()\u6267\u884c\u5f02\u5e38, \u4efb\u52a1\u540d\u79f0: [{}]", (Object)shardingContext.getJobName(), (Object)e2);
            }
        }
    }
    
    private void readDbShardIfNecessary(final ShardingContext shardingContext, final JobProcessData inf) {
        final String jobName = shardingContext.getJobName();
        final ZsfJobProperties zsfJobProperties = JobInfPool.get(jobName);
        final int shardingTotalCount = shardingContext.getShardingTotalCount();
        if (shardingTotalCount > 1 && zsfJobProperties.isShardingTdSql()) {
            String setName = null;
            List<Integer> list = null;
            final int shardingItem = shardingContext.getShardingItem();
            final Map<String, List<Integer>> partition = ShardStorage.getPartition(jobName, shardingItem, shardingTotalCount);
            if (CollectionUtils.isEmpty((Map)partition)) {
                AbstractSimpleJob.log.error("\u672a\u67e5\u8be2\u5230\u5206\u7247\u6570\u636e\uff0c\u5206\u7247\u4efb\u52a1[{}]\u8df3\u8fc7\u6b64\u6b21\u6267\u884c\u5468\u671f\uff0c\u5f53\u524d\u5206\u7247\u6570[{}]\uff01", (Object)jobName, (Object)shardingItem);
                inf.setSkip(true);
                return;
            }
            final Iterator<String> iterator = partition.keySet().iterator();
            while (iterator.hasNext()) {
                final String name = setName = iterator.next();
                list = partition.get(name);
            }
            final List<String> shardingDbItem = list.stream().map(x -> "p" + x).collect((Collector<? super Object, ?, List<String>>)Collectors.toList());
            inf.setShardingDbSet(setName);
            inf.setShardingDbNo(list);
            inf.setShardingDbItem(shardingDbItem);
            AbstractSimpleJob.log.info("\u5f53\u524d\u4efb\u52a1[{}]\u5206\u7247\u60c5\u51b5\uff1a\u6570\u636e\u5206\u533aset\uff1a[{}] | \u6570\u636e\u5206\u7247\u5217\u8868\uff1a[{}] | \u5f53\u524d\u5206\u7247\u4efb\u52a1\u6807\u53f7\uff1a[{}]", new Object[] { jobName, setName, JsonUtils.objectToJson((Object)shardingDbItem), shardingItem });
        }
    }
    
    private void persistBizDate(final JobProcessData data) {
        final String bizDate = data.getBizDate();
        final ZsfJobNodePath zsfJobNodePath = new ZsfJobNodePath(data.getContext().getJobName());
        ((ZookeeperRegistryCenter)SpringContextHelper.getBean("zookeeperRegistryCenter", (Class)ZookeeperRegistryCenter.class)).persist(zsfJobNodePath.getBizDateNodePath(), bizDate);
    }
    
    public String getBizDate() {
        return DateUtils.getCurDT();
    }
    
    public JobProcessData before(final JobProcessData inf) throws Exception {
        final ShardingContext shardingContext = inf.getContext();
        AbstractSimpleJob.log.info("ZsfJob: \u51c6\u5907\u6267\u884c\u4efb\u52a1[{}].before(), \u5f53\u524d\u5206\u7247[{}]", (Object)shardingContext.getJobName(), (Object)shardingContext.getShardingItem());
        TraceUtil.beginApplilcatonName(ZsfEnvConstants.get(ZsfEnvConstants.APPLICATION_NAME_KEY), ZsfEnvConstants.get(ZsfEnvConstants.PROFILES_ACTIVE_KEY));
        final String jobName = shardingContext.getJobName();
        final ZsfJobNodePath zsfJobNodePath = new ZsfJobNodePath(jobName);
        final String zycfcTraceId = jobName + "#" + ((ZookeeperRegistryCenter)SpringContextHelper.getBean("zookeeperRegistryCenter", (Class)ZookeeperRegistryCenter.class)).getDirectly(zsfJobNodePath.getElectBatchNoNodePath());
        AbstractSimpleJob.log.info("start--zycfcTraceId:{}", (Object)zycfcTraceId);
        TraceUtil.beginZycfcTrace(zycfcTraceId);
        ZsfRootContext.put(TraceUtil.getZycfcTraceKeyName(), zycfcTraceId);
        final String bizDate = inf.getBizDate();
        final ZsfJobProperties job = JobInfPool.get(jobName);
        this.persistPerBatchNoIfNecessary(inf, job);
        if (this.isSwitchOff()) {
            AbstractSimpleJob.log.error("\u670d\u52a1\u7ea7\u4f5c\u4e1a\u5f00\u5173\u5df2\u5173\u95ed\uff0c\u8be5\u6b21\u4efb\u52a1\u4e0d\u518d\u6267\u884c");
            inf.setSkip(true);
        }
        else if (CallType.CALL_CHAIN_ROOT.equals(job.getCallType()) || CallType.CALL_CHAIN_BRANCH.equals(job.getCallType())) {
            inf.setSkip(this.isSkip(bizDate, jobName));
        }
        final boolean identmentResult = this.idempotent(job.getIdempotent(), jobName, shardingContext.getShardingItem());
        inf.setIdentmentResult(identmentResult);
        AbstractSimpleJob.log.info(shardingContext.getShardingItem() + "-\u5e42\u7b49\u7ed3\u679c:{}", (Object)identmentResult);
        if (identmentResult) {
            throw new ServiceException((IExceptionCode)JobExceptionCode.JOB0001);
        }
        if (!inf.isSkip()) {
            this.readDbShardIfNecessary(shardingContext, inf);
        }
        return inf;
    }
    
    private void persistPerBatchNoIfNecessary(final JobProcessData data, final ZsfJobProperties job) {
        if (!CallType.CALL_CHAIN_NO.equals(job.getCallType())) {
            String batchNo = null;
            final String jobName = job.getJobName();
            final ZsfJobNodePath zsfJobNodePath = new ZsfJobNodePath(jobName);
            final String chainJson = ((ZookeeperRegistryCenter)SpringContextHelper.getBean("zookeeperRegistryCenter", (Class)ZookeeperRegistryCenter.class)).get(zsfJobNodePath.getChainNodePath());
            if (StringUtils.isEmpty(chainJson)) {
                AbstractSimpleJob.log.info("chainJson--is --null");
                return;
            }
            final TJobChainDetail chainDetail = (TJobChainDetail)JsonUtils.jsonToObject(chainJson, (Class)TJobChainDetail.class);
            if (CallType.CALL_CHAIN_ROOT.equals(job.getCallType())) {
                batchNo = PeriodUtils.getBatchNo(data.getBizDate(), chainDetail.getPeriod());
            }
            else if (CallType.CALL_CHAIN_BRANCH.equals(job.getCallType())) {
                final String rootJobName = chainDetail.getRootJobName();
                if (StringUtils.isEmpty(rootJobName)) {
                    AbstractSimpleJob.log.info("rootJobName--is --null");
                    return;
                }
                final ZsfJobNodePath zsfFirstJobNodePath = new ZsfJobNodePath(rootJobName);
                if (!((ZookeeperRegistryCenter)SpringContextHelper.getBean("zookeeperRegistryCenter", (Class)ZookeeperRegistryCenter.class)).isExisted(zsfFirstJobNodePath.getBatchNoNodePath())) {
                    AbstractSimpleJob.log.info("----not is existed---");
                    return;
                }
                batchNo = ((ZookeeperRegistryCenter)SpringContextHelper.getBean("zookeeperRegistryCenter", (Class)ZookeeperRegistryCenter.class)).get(zsfFirstJobNodePath.getBatchNoNodePath());
            }
            if (StringUtils.isNotEmpty(batchNo)) {
                ((ZookeeperRegistryCenter)SpringContextHelper.getBean("zookeeperRegistryCenter", (Class)ZookeeperRegistryCenter.class)).persist(zsfJobNodePath.getPreBatchNoNodePath(), batchNo);
            }
            AbstractSimpleJob.log.info("persistPerBatchNoIfNecessary\uff0c\u8bb0\u5f55\u6279\u6b21\u53f7{}, jobName{}", (Object)batchNo, (Object)jobName);
        }
    }
    
    private boolean idempotent(final IdempotentType idempotentLevel, final String jobName, final int sharedingItem) {
        if (!IdempotentType.S.equals(idempotentLevel)) {
            final String key = jobName + "-" + sharedingItem + "-" + DateUtils.getCurDT() + DateUtils.getCurTime("HHmm");
            AbstractSimpleJob.log.info("\u5e42\u7b49key:{}", (Object)key);
            final String group = "zsf-job";
            synchronized (AbstractSimpleJob.class) {
                if (LocalCacheUtil.get(group, key) != null) {
                    return true;
                }
                LocalCacheUtil.put(group, key, (Object)"1", Long.valueOf(120L));
            }
        }
        return false;
    }
    
    private String getMilliSecond() {
        return DateUtils.getCurTime("HHmmssSSS");
    }
    
    private boolean isSwitchOff() {
        return "OFF".equals(((ZsfJobSwitch)SpringContextHelper.getBean("zsfJobSwitch", (Class)ZsfJobSwitch.class)).getStatus());
    }
    
    private boolean isSkip(final String bizDate, final String jobName) {
        final ZsfJobNodePath zsfJobNodePath = new ZsfJobNodePath(jobName);
        final String chainJson = ((ZookeeperRegistryCenter)SpringContextHelper.getBean("zookeeperRegistryCenter", (Class)ZookeeperRegistryCenter.class)).get(zsfJobNodePath.getChainNodePath());
        if (StringUtils.isEmpty(chainJson)) {
            AbstractSimpleJob.log.info("\u4f5c\u4e1a\u94fe\u8c03\u7528\uff0c\u4f46\u7f3a\u5c11\u4f5c\u4e1a\u94fe\u4fe1\u606f\u914d\u7f6e," + jobName);
            throw new IllegalArgumentException("\u4f5c\u4e1a\u94fe\u8c03\u7528\uff0c\u4f46\u7f3a\u5c11\u4f5c\u4e1a\u94fe\u4fe1\u606f\u914d\u7f6e," + jobName);
        }
        final TJobChainDetail chainDetail = (TJobChainDetail)JsonUtils.jsonToObject(chainJson, (Class)TJobChainDetail.class);
        final String tempBatchNo = PeriodUtils.getBatchNo(bizDate, chainDetail.getPeriod());
        final String result = ((ZookeeperRegistryCenter)SpringContextHelper.getBean("zookeeperRegistryCenter", (Class)ZookeeperRegistryCenter.class)).get(zsfJobNodePath.getResultNodePath());
        if (StringUtils.isEmpty(result)) {
            AbstractSimpleJob.log.info("result is null");
            return false;
        }
        final String[] arr = result.split("@");
        final String batchNo = arr[1];
        final String succ = arr[4];
        if ("S".equals(succ) && tempBatchNo.equals(batchNo)) {
            AbstractSimpleJob.log.info("return--true--");
            return true;
        }
        return false;
    }
    
    public void after(final JobProcessData data) {
        final ShardingContext shardingContext = data.getContext();
        this.saveResult(data);
        AbstractSimpleJob.log.info(shardingContext.getJobName() + " execute time=" + (System.currentTimeMillis() - data.getStartTime()));
    }
    
    private void saveResult(final JobProcessData data) {
        if (ObjectUtils.isEmpty((Object)data) || data.isSkip()) {
            return;
        }
        String chainNo = "00";
        if (data.isIdentmentResult()) {
            this.doCollenctMessage(data, "D", chainNo, DateUtils.getCurDT() + DateUtils.getCurTM(), DateUtils.getCurDT(), 0, 0);
            AbstractSimpleJob.log.info("\u5e42\u7b49\u4fe1\u606f\u91c7\u96c6\u6210\u529f\uff0cand return ...");
            return;
        }
        final ShardingContext shardingContext = data.getContext();
        final int shardingTotalCount = shardingContext.getShardingTotalCount();
        String batchNo = null;
        final ZsfJobProperties job = JobInfPool.get(shardingContext.getJobName());
        final ZsfJobNodePath zsfJobNodePath = new ZsfJobNodePath(shardingContext.getJobName());
        if (!CallType.CALL_CHAIN_NO.equals(job.getCallType())) {
            final String chainJson = ((ZookeeperRegistryCenter)SpringContextHelper.getBean("zookeeperRegistryCenter", (Class)ZookeeperRegistryCenter.class)).get(zsfJobNodePath.getChainNodePath());
            if (StringUtils.isEmpty(chainJson)) {
                AbstractSimpleJob.log.info("chainJson--is --null");
                return;
            }
            final TJobChainDetail chainDetail = (TJobChainDetail)JsonUtils.jsonToObject(chainJson, (Class)TJobChainDetail.class);
            chainNo = chainDetail.getChainNo();
            if (CallType.CALL_CHAIN_ROOT.equals(job.getCallType())) {
                batchNo = PeriodUtils.getBatchNo(data.getBizDate(), chainDetail.getPeriod());
                ((ZookeeperRegistryCenter)SpringContextHelper.getBean("zookeeperRegistryCenter", (Class)ZookeeperRegistryCenter.class)).persist(zsfJobNodePath.getBatchNoNodePath(), batchNo);
            }
            else if (CallType.CALL_CHAIN_BRANCH.equals(job.getCallType())) {
                final String rootJobName = chainDetail.getRootJobName();
                if (StringUtils.isEmpty(rootJobName)) {
                    AbstractSimpleJob.log.info("rootJobName--is --null");
                    return;
                }
                final ZsfJobNodePath zsfFirstJobNodePath = new ZsfJobNodePath(rootJobName);
                if (!((ZookeeperRegistryCenter)SpringContextHelper.getBean("zookeeperRegistryCenter", (Class)ZookeeperRegistryCenter.class)).isExisted(zsfFirstJobNodePath.getBatchNoNodePath())) {
                    AbstractSimpleJob.log.info("----not is existed---");
                    return;
                }
                batchNo = ((ZookeeperRegistryCenter)SpringContextHelper.getBean("zookeeperRegistryCenter", (Class)ZookeeperRegistryCenter.class)).getDirectly(zsfFirstJobNodePath.getBatchNoNodePath());
            }
        }
        if (CallType.CALL_CHAIN_NO.equals(job.getCallType())) {
            batchNo = ((ZookeeperRegistryCenter)SpringContextHelper.getBean("zookeeperRegistryCenter", (Class)ZookeeperRegistryCenter.class)).getDirectly(zsfJobNodePath.getElectBatchNoNodePath());
        }
        final String lockKey = chainNo + "-" + batchNo + "-" + shardingContext.getJobName();
        String sts = "R";
        int curSucc = 0;
        int total = 0;
        final IDistributedLock lock = DistributedLockUtil.getNewDistributedLock("ZSF_JOB_LOCK_GROUP", lockKey, 30000L);
        try {
            while (!lock.tryLock()) {
                AbstractSimpleJob.log.warn("\u7b49\u5f85\u66f4\u65b0\u8c03\u5ea6\u8fd0\u884c\u7ed3\u679c, \u7b49\u5f85\u83b7\u53d6\u5206\u5e03\u5f0f\u9501, \u4f11\u7720100\u6beb\u79d2, \u4f5c\u4e1a\u540d\u79f0: [{}], \u603b\u5206\u7247\u6570: [{}], \u5f53\u524d\u5206\u7247\u6570: [{}]", new Object[] { job.getJobName(), shardingTotalCount, shardingContext.getShardingItem() });
                LockSupport.parkNanos(100000000L);
            }
            AbstractSimpleJob.log.info("\u5f00\u59cb\u66f4\u65b0\u8c03\u5ea6\u8fd0\u884c\u7ed3\u679c, \u83b7\u53d6\u5206\u5e03\u5f0f\u9501\u6210\u529f\uff0c\u4f5c\u4e1a\u540d\u79f0: [{}], \u603b\u5206\u7247\u6570: [{}], \u5f53\u524d\u5206\u7247\u6570: [{}]", new Object[] { job.getJobName(), shardingTotalCount, shardingContext.getShardingItem() });
            String result = ((ZookeeperRegistryCenter)SpringContextHelper.getBean("zookeeperRegistryCenter", (Class)ZookeeperRegistryCenter.class)).getDirectly(zsfJobNodePath.getResultNodePath());
            AbstractSimpleJob.log.info("\u66f4\u65b0\u8c03\u5ea6\u8fd0\u884c\u7ed3\u679c\uff0c\u4f5c\u4e1a\u540d\u79f0: [{}], \u603b\u5206\u7247\u6570: [{}], \u5f53\u524d\u5206\u7247\u6570: [{}]\uff0c\u53d8\u66f4\u524d\u7684\u7684\u7ed3\u679c\u4e3a[{}]", new Object[] { job.getJobName(), shardingTotalCount, shardingContext.getShardingItem(), result });
            if (shardingTotalCount > 1 && !StringUtils.isEmpty(result)) {
                final String[] arr = result.split("@");
                final String tmpBatchNo = arr[1];
                if (batchNo.equals(tmpBatchNo)) {
                    total = Integer.parseInt(arr[2]);
                    curSucc = Integer.parseInt(arr[3]);
                }
            }
            if (total >= shardingContext.getShardingTotalCount()) {
                this.doCollenctMessage(data, "O", chainNo, batchNo, DateUtils.getCurDT(), curSucc, total);
                return;
            }
            ++total;
            if (data.isResultFlag()) {
                ++curSucc;
            }
            if (curSucc == shardingTotalCount) {
                sts = "S";
            }
            result = chainNo + "@" + batchNo + "@" + total + "@" + curSucc + "@" + sts;
            AbstractSimpleJob.log.info("\u66f4\u65b0\u8c03\u5ea6\u8fd0\u884c\u7ed3\u679c\uff0c\u4f5c\u4e1a\u540d\u79f0: [{}], \u603b\u5206\u7247\u6570: [{}], \u5f53\u524d\u5206\u7247\u6570: [{}]\uff0c\u53d8\u66f4\u540e\u7684\u7684\u7ed3\u679c\u4e3a[{}]", new Object[] { job.getJobName(), shardingTotalCount, shardingContext.getShardingItem(), result });
            ((ZookeeperRegistryCenter)SpringContextHelper.getBean("zookeeperRegistryCenter", (Class)ZookeeperRegistryCenter.class)).persist(zsfJobNodePath.getResultNodePath(), result);
        }
        catch (Exception e) {
            AbstractSimpleJob.log.error("\u66f4\u65b0\u8c03\u5ea6\u8fd0\u884c\u7ed3\u679c\u5f02\u5e38, jobname is [{}]", (Object)job.getJobName(), (Object)e);
        }
        finally {
            this.releaseLock(lock);
        }
        final String bizDate = ((ZookeeperRegistryCenter)SpringContextHelper.getBean("zookeeperRegistryCenter", (Class)ZookeeperRegistryCenter.class)).getDirectly(zsfJobNodePath.getBizDateNodePath());
        this.doCollenctMessage(data, data.isResultFlag() ? "S" : "F", chainNo, batchNo, bizDate, curSucc, total);
    }
    
    private void doCollenctMessage(final JobProcessData data, final String sts, final String chainNo, final String batchNo, final String bizDate, final int curSucc, final int total) {
        final String endTm = DateUtils.getCurDT() + DateUtils.getCurTM();
        final ZsfJobDatatRequest request = new ZsfJobDatatRequest(data.getContext().getJobName(), "2", data.getContext().getShardingItem(), chainNo, batchNo, bizDate, sts, curSucc, data.getStartTm(), endTm, System.currentTimeMillis() - data.getStartTime(), NetUtils.getLocalHost());
        request.setTotal(data.getContext().getShardingTotalCount());
        request.setCurIndex(total);
        DateCollectionService.doSpanCollenctMessage(request);
    }
    
    private void releaseLock(final IDistributedLock lock) {
        try {
            if (!ObjectUtils.isEmpty((Object)lock)) {
                lock.releaseLock();
            }
        }
        catch (Exception e) {
            AbstractSimpleJob.log.error(e.getMessage(), (Throwable)e);
        }
    }
    
    public abstract void process(final JobProcessData p0);
    
    static {
        log = LoggerFactory.getLogger((Class)AbstractSimpleJob.class);
    }
}
